//
//  TXAuthViewController.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/4/2.
//

import SwiftUI

/// **封装 UIKit 逻辑**
struct TXAuthViewController: UIViewControllerRepresentable {
    @Binding var token: String?
    @Binding var show: Bool
    class Coordinator: NSObject {
        var viewController: UIViewController!
        var parent: TXAuthViewController
        init(parent: TXAuthViewController) {
            self.parent = parent
        }

        func startLogin(from viewController: UIViewController) {
            self.viewController = viewController
            TXCommonHandler.sharedInstance().getLoginToken(withTimeout: 5.0, controller: viewController, model: _makeModel()) { result in
                guard let code = result["resultCode"] as? String else {
                    return
                }
                if code == PNSCodeLoginControllerPresentSuccess {
                    Logger.log(.debug, message: "弹起授权页成功", tag: .oneKeyView)
                }
                if code == PNSCodeLoginControllerClickCancel {
                    Logger.log(.debug, message: "点击了授权页的返回", tag: .oneKeyView)
                }
                if code == PNSCodeLoginControllerClickChangeBtn {
                    Logger.log(.debug, message: "点击切换其他登录方式按钮", tag: .oneKeyView)
                }
                if code == PNSCodeLoginControllerClickLoginBtn {
                    guard let isCheck = result["isChecked"] as? Bool else {
                        return
                    }
                    if isCheck {
                        print("点击了登录按钮，check box选中，SDK内部接着会去获取登录Token")
                    } else {
                        print("点击了登录按钮，check box未选中，SDK内部不会去获取登录Token")
                    }
                }
                if code == PNSCodeLoginControllerClickCheckBoxBtn {
                    Logger.log(.debug, message: "点击check box", tag: .oneKeyView)
                }
                if code == PNSCodeLoginControllerClickProtocol {
                    Logger.log(.debug, message: "点击了协议富文本", tag: .oneKeyView)
                }
                if code == PNSCodeSuccess {
                    let token = result["token"]
                    Logger.log(.debug, message: "点击登录按钮获取登录Token成功：\(token ?? "null")", tag: .oneKeyView)
                    self.parent.token = token as? String
                    self._moreTypeLoginClick()
                }
                if code == PNSCodeInterfaceLimited {
                    Logger.log(.debug, message: "一键登录获取token超时" ,tag: .oneKeyView)
                }
            }
        }

        // 构建model样式
        private func _makeModel() -> TXCustomModel {
            let model = TXCustomModel()
            model.supportedInterfaceOrientations = UIInterfaceOrientationMask.portrait
            model.suspendDisMissVC = false
            model.hideNavBackItem = true
            model.navColor = .white
            model.navTitle = NSAttributedString()
            model.navBackImage = UIImage(named: "icon_nav_back_gray")!
            model.backgroundColor = .white
            // TODO:
            model.logoImage = UIImage(named: "login_logo")!
            model.logoFrameBlock = { (screenSize: CGSize, superViewSize: CGSize, _: CGRect) -> CGRect in
                // 竖屏
                if screenSize.height > screenSize.width {
                    let width = 195.0
                    let height = 58.0
                    let x = superViewSize.width / 2.0 - width / 2.0
                    let y = 44.0

                    return CGRect(origin: CGPoint(x: x, y: y), size: CGSizeMake(width, height))
                }
                return CGRect()
            }

            let attributes: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.black.withAlphaComponent(0.4),
                .font: UIFont.systemFont(ofSize: 14),
            ]
            let sloganStr = NSLocalizedString("China Telecom Certification Authority", comment: "")
            model.sloganText = NSAttributedString(string: sloganStr, attributes: attributes)
            model.sloganFrameBlock = { (screenSize: CGSize, superViewSize: CGSize, frame: CGRect) -> CGRect in
                // 竖屏
                if screenSize.height > screenSize.width {
                    let width = frame.width
                    let height = 22.0
                    let x = superViewSize.width / 2.0 - width / 2.0
                    let y = 198.0
                    return CGRect(origin: CGPoint(x: x, y: y), size: CGSizeMake(width, height))
                }
                return CGRect()
            }

            // 手机号
            model.numberColor = UIColor.black.withAlphaComponent(0.9)
            model.numberFont = UIFont.systemFont(ofSize: 24)
            model.numberFrameBlock = { (screenSize: CGSize, superViewSize: CGSize, frame: CGRect) -> CGRect in
                // 竖屏
                if screenSize.height > screenSize.width {
                    let width = frame.width
                    let height = 32.0
                    let x = superViewSize.width / 2.0 - width / 2.0
                    let y = 158.0

                    return CGRect(origin: CGPoint(x: x, y: y), size: CGSizeMake(width, height))
                }
                return CGRect()
            }

            // 一键登录按钮
            let attributesBtn: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.white,
                .font: UIFont.systemFont(ofSize: 16),
            ]
            let loginBtnStr = NSLocalizedString("one key login", comment: "")
            model.loginBtnText = NSAttributedString(string: loginBtnStr, attributes: attributesBtn)
            if let img = UIImage(named: "btnBg"), let imgdisable = UIImage(named: "btnBg_disable") {
                model.loginBtnBgImgs = [img, imgdisable, img]
            }

            model.autoHideLoginLoading = false
            model.loginBtnFrameBlock = { (screenSize: CGSize, superViewSize: CGSize, _: CGRect) -> CGRect in
                // 竖屏
                if screenSize.height > screenSize.width {
                    let width = superViewSize.width - 48
                    let height = 40.0
                    let x = superViewSize.width / 2.0 - width / 2.0
                    let y = 244.0

                    return CGRect(origin: CGPoint(x: x, y: y), size: CGSizeMake(width, height))
                }
                return CGRect()
            }
            // 更多登录方式
            model.changeBtnIsHidden = true
            let attributesMore: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.black.withAlphaComponent(0.6),
                .font: UIFont.systemFont(ofSize: 16),
            ]
            let loginMoreStr = NSLocalizedString("more login type", comment: "")
            let moreBtn = UIButton(type: .system)
            moreBtn.setTitle(loginMoreStr, for: .normal)
            moreBtn.setTitleColor(UIColor.black.withAlphaComponent(0.6), for: .normal)
            moreBtn.setAttributedTitle(NSAttributedString(string: loginMoreStr, attributes: attributesMore), for: .normal)
            moreBtn.addTarget(self, action: #selector(_moreTypeLoginClick), for: .touchUpInside)

            model.customViewBlock = { superCustomView in
                superCustomView.addSubview(moreBtn)
            }
            model.customViewLayoutBlock = { _, _, _, _, _, _, _, loginFrame, _, _ in
                moreBtn.frame = CGRectMake(CGRectGetMinX(loginFrame),
                                           CGRectGetMaxY(loginFrame) + 20,
                                           CGRectGetWidth(loginFrame),
                                           30)
            }

            // 协议勾选框 checkbox
            model.checkBoxImages = [UIImage(named: "check_box")!, UIImage(named: "check_box_sel")!]
            let privacyOneStr = NSLocalizedString("<User Agreement>", comment: "")
            model.privacyOne = [privacyOneStr, USER_PROTOCOL]
            model.privacyOneColor = SWColor(hexString: "#6758D4")!
            let privacyTwoStr = NSLocalizedString("<Privacy Agreement>", comment: "")
            model.privacyTwo = [privacyTwoStr, PRIVACY_PROTOCOL]
            model.privacyTwoColor = SWColor(hexString: "#6758D4")!

            model.privacyOperatorColor = SWColor(hexString: "#6758D4")!
            return model
        }

        @objc private func _moreTypeLoginClick() {
           self.parent.show = false
            DispatchQueue.main.async {
                self.viewController.dismiss(animated: true)
            }
        }
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: Context) -> UIViewController {
        let viewcontroller = UIViewController()
        DispatchQueue.main.async {
            context.coordinator.startLogin(from: viewcontroller)
        }

        return viewcontroller
    }

    func updateUIViewController(_: UIViewController, context _: Context) {}
}
